package com.shao.im.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.shao.commons.domain.Codes;
import com.shao.commons.exception.ServiceException;
import com.shao.commons.utils.CodeUtils;
import com.shao.im.dao.UserDao;
import com.shao.im.entity.Email;
import com.shao.im.entity.User;
import com.shao.im.service.EmailService;
import com.shao.im.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-07-26 12:48:01
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private EmailService emailService;

    @Override
    public boolean save(User entity) {
        Long userCount = this.query().eq("username", entity.getUsername()).count();
        // 校验用户名是否存在
        if (userCount != 0) {
            throw new ServiceException(Codes.USER_EXIST);
        }
        // 校验邮箱是否存在
        Long emailCount = this.query().eq("email", entity.getEmail()).count();
        if (emailCount != 0) {
            throw new ServiceException(Codes.EMAIL_EXIST);
        }
        return super.save(entity);
    }

    @Override
    public User queryByUserName(String username) {
        return this.query().eq("username", username).one();
    }

    @Override
    public int sendEmailByUsername(String username) {
        User user = this.query().eq("username", username).one();
        if (user == null) throw new ServiceException(Codes.USER_NOT_FOUND);
        // 获取收件人的邮箱
        String addresseeEmail = user.getEmail();
        // 生成验证码
        int code = (int)(Math.random() * 900000) + 100000;
        // 存储验证码
        CodeUtils.setCode(username, code, 5, TimeUnit.MINUTES); // 5分钟
        // 封装一封邮件
        Email email = new Email()
                .setSubject("【腾讯DD官方邮件】找回密码")
                .setTo(addresseeEmail)
                .setContent("找回密码的验证码内容：" + code + ", 如果不是本人操作，请忽略！");

        emailService.sendEmail(email);
        return 1;
    }

    @Override
    public List<User> search(String keyword) {
        if (StringUtils.isNullOrEmpty(keyword)) {
            // 如果是空就直接返回空
            return new ArrayList<>();
        }

        return this.query()
                .like("username", keyword)
                .or()
                .like("nickname", keyword)
                .list();
    }
}

